package com.hisan.freeride.home.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.ImageUtils;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.CompressPhotoUtils;
import com.hisan.freeride.common.utils.GlideImageLoader;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.databinding.EvaluationBinding;
import com.hisan.freeride.home.model.ImageUrl;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.callback.ConfigButton;
import com.mylhyl.circledialog.callback.ConfigDialog;
import com.mylhyl.circledialog.params.ButtonParams;
import com.mylhyl.circledialog.params.DialogParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 创建时间 : 2017/6/23
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：评价页面
 */
public class EvaluationActivity extends BaseActivity<EvaluationBinding>  {
    public  int max = 0;
    public  List<Bitmap> bmp = new ArrayList<Bitmap>();
    //图片sd地址
    public  List<String> drr = new ArrayList<String>();
    //图片集合
    private ArrayList<ImageItem> imageItems;
    private GridAdapter adapter;
    /**
     * 获取从服务器传过来的地址集合
     */
    private List<String>urlpaths;
    private ArrayList<File> files =new ArrayList<>();
    private String imageurlpath="";
    private int id;
    private Intent intent;
    private android.app.ProgressDialog progressDialog;


    @Override
    protected int getLayoutId() {
        return R.layout.evaluation;
    }

    @Override
    protected void initView() {
        //根据屏幕进行四等分
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        mBinding.evaluationGrid.setColumnWidth(width/5);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        mBinding.evaluationGrid.setOnItemClickListener((adapterView, view, i, l) -> {
            if (i == bmp.size()) {
                toImage();
            }
        });
        adapter = new GridAdapter(this);
        adapter.update();
        mBinding.evaluationGrid.setAdapter(adapter);
        Bundle bundle= getIntent().getExtras();
        if (!CollectionUtils.isNullOrEmpty(bundle)){
            id=bundle.getInt("id");
        }
        mBinding.bar.setIntegerMark(false);
    }

    @Override
    protected void initEvent() {
        mBinding.submit.setOnClickListener(v -> {
            String content=mBinding.hint.getText().toString();
            float mark= mBinding.bar.getStarMark();
            if (CollectionUtils.isNullOrEmpty(id)
                    ||CollectionUtils.isNullOrEmpty(content)||CollectionUtils.isNullOrEmpty(mark)){
                showToast("缺乏参数");
                return;
            }
            if (!CollectionUtils.isNullOrEmpty(imageItems)){
                new CompressPhotoUtils().CompressPhoto(EvaluationActivity.this, imageItems, new CompressPhotoUtils.CompressCallBack() {
                    @Override
                    public void success(List<String> list) {
                        //执行上传的方法
                        if (list.size()>0){
                            upload(id,content,mark,list);
                        }else {
                            shoewErrorToast("请选择图片");
                        }
                    }
                });
            }else {
                if (CollectionUtils.isNullOrEmpty(content)){
                    shoewErrorToast("请输入您对车主的评价");
                    return;
                }
                Submit(id,content,imageurlpath,mark);
            }

        });
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
    }

    @Override
    protected void loadData(boolean isRefresh) {}
    private void upload(int id, String content, float mark, List<String> list) {
        if (list.size() >9) {
            for (int i = 0; i < 9; i++) {
                files.add(new File(list.get(i)));
            }
        }else {
            for (int i = 0; i < list.size(); i++) {
                files.add(new File(list.get(i)));
            }
        }
        //拼接参数
        OkGo.<ImageUrl>post(AppConfig.UpLoad)
                .tag(this)
                .addFileParams("image[]", files)
                .execute(new DialogCallback<ImageUrl>(EvaluationActivity.this) {
                    @Override
                    public void onStart(Request<ImageUrl, ? extends Request> request) {
                        super.onStart(request);
                        if (progressDialog==null) progressDialog = new android.app.ProgressDialog(EvaluationActivity.this);
                        progressDialog.setProgressStyle(android.app.ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.setMessage("图片上传中");
                        progressDialog.setCancelable(false);
                        progressDialog.setMax(100);
                        progressDialog.show();
                    }
                    @Override
                    public void onSuccess(Response<ImageUrl> response) {
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                                urlpaths=new ArrayList<>();
                                String data= GsonUtils.GsonString(response.body());
                                ImageUrl imageUrl=GsonUtils.GsonToBean(data,ImageUrl.class);
                                for (int i=0;i<imageUrl.getFile().size();i++){
                                    urlpaths.add(imageUrl.getFile().get(i));
                                }
                                imageurlpath = formatStr(urlpaths);
                                Submit(id,content,imageurlpath,mark);
                        }
                    }
                    @Override
                    public void onError(Response<ImageUrl> response) {
                        super.onError(response);
                        progressDialog.dismiss();
                        shoewErrorToast("上传失败");
                    }
                    @Override
                    public void uploadProgress(Progress progress) {
                        progressDialog.setProgress((int) (progress.fraction * 10000));
                    }
                });
    }


    //发布评论
    private void Submit(int id, String content, String imageurlpath, float mark) {
        OkGo.post(AppConfig.Savecomment)
                .tag(this)
                .params("id",id)
                .params("content",content)
                .params("album",imageurlpath)
                .params("score",mark)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        progressDialog.dismiss();
                        if (isOk(response)){
                            showToast("评价成功,请等待后台审核！！");
                            if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                            setResult(99,intent);
                            finishActivity(true);
                        }else {
                            showError(response);
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        progressDialog.dismiss();
                        showError(response);
                    }
                });
    }

    private void toImage() {
        final String[] items = {"相册", "相机"};
        new CircleDialog.Builder(this)
                .configDialog(new ConfigDialog() {
                    @Override
                    public void onConfig(DialogParams params) {
                    }
                })
                .setTitle("选择照片")
                .setTitleColor(getResources().getColor(R.color.home_titel))
                .setItems(items, (parent, view, position, id1) -> {
                    if (!CollectionUtils.isNullOrEmpty(items)){
                        if (items[position].equals("相册")){
                            Intent intent1 = new Intent(EvaluationActivity.this,ImageGridActivity.class);
                            startActivityForResult(intent1, 100);
                        }else{
                            Intent intent1 = new Intent(EvaluationActivity.this, ImageGridActivity.class);
                            intent1.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true); // 是否是直接打开相机
                            startActivityForResult(intent1, 100);
                        }
                    }
                })
                .setNegative("取消", null)
                .configNegative(new ConfigButton() {
                    @Override
                    public void onConfig(ButtonParams params) {
                        //取消按钮字体颜色
                        params.textColor = getResources().getColor(R.color.home_titel);
                    }
                })
                .show();
    }


    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器
        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }
        public void update() {
            loading();
        }
        public int getCount() {
            return (bmp.size() + 1);
        }
        public Object getItem(int arg0) {
            return arg0;
        }
        public long getItemId(int arg0) {
            return arg0;
        }
        /**
         * ListView Item设置
         */
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                holder.delete_image_view= (LinearLayout) convertView.findViewById(R.id.delete_image_view);
                holder.delete_image_view.setOnClickListener(view -> {
                    if (!CollectionUtils.isNullOrEmpty(bmp)) bmp.remove(position);
                    if (!CollectionUtils.isNullOrEmpty(files))files.remove(files.get((position-1)));
                    mBinding.evaluationGrid.setAdapter(adapter);
                });
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == bmp.size()) {
                if (position>8){
                    holder.image.setVisibility(View.GONE);
                    holder.delete_image_view.setVisibility(View.GONE);
                }else {
                    holder.image.setImageBitmap(BitmapFactory.decodeResource(
                            getResources(), R.mipmap.frend_upload));
                    holder.delete_image_view.setVisibility(View.GONE);
                }
            } else {
                if (position<9){
                    holder.image.setImageBitmap(bmp.get(position));
                    convertView.setVisibility(View.VISIBLE);
                    holder.delete_image_view.setVisibility(View.VISIBLE);
                }else {
                    holder.image.setVisibility(View.GONE);
                    convertView.setVisibility(View.GONE);
                    holder.delete_image_view.setVisibility(View.GONE);
                    shoewErrorToast("最多选择9张图片");
                }
            }
            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
            public LinearLayout delete_image_view;
        }

        public void loading() {
            if (max == drr.size()) {
                adapter.notifyDataSetChanged();
            } else {
                try {
                    String path = drr.get(max);
                    Bitmap bm = ImageUtils.getBitmap(path,50,50);
                    bmp.add(bm);
                    max += 1;
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems != null && imageItems.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < imageItems.size(); i++) {
                        if (i == imageItems.size() - 1)
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems.get(i).path);
                        else
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems.get(i).path).append("\n");
                    }
                    formUpload();
                } else {
                    showToast("没有选择图片");
                }
            }
        }
    }

    //上传图片
    private  void formUpload() {
        if (!CollectionUtils.isNullOrEmpty(imageItems)) {
            for (int i = 0; i < imageItems.size(); i++) {
                drr.add(imageItems.get(i).path);
                adapter.update();
            }
        }
    }

    private String formatStr(List<String> list) {
        String result = "";
        if(list.size() > 0) {
            for (int i=0;i<list.size();i++){
                if(list.get(i) != null){
                    result += list.get(i) + ",";
                    Log.d("result",result);
                }
            }
            result = result.substring(0,result.length()-1);
        }
        return result;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!CollectionUtils.isNullOrEmpty(progressDialog)&&progressDialog.isShowing())progressDialog.dismiss();
    }
}